<?php

namespace Rjyst\RjSentence\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;

class InstallCommand extends Command
{
    protected $signature = 'rj-sentence:install {--force : Force install without confirmation} {--skip-seed : Skip running seeders}';
    protected $description = 'Install RjYst Sentence Package';

    public function handle()
    {
        $this->info('🚀 开始安装 RjYst Sentence 扩展包...');

        // 1. 检查依赖扩展包
        if (!$this->checkDependencies()) {
            return;
        }

        // 2. 发布并检查迁移文件
        $this->publishMigrations();

        // 3. 发布模型文件
        $this->publishModels();

        // 4. 发布管理后台文件
        $this->publishAdminFiles();

        // 5. 发布 Seeders
        $this->publishSeeders();

        // 6. 添加路由
        $this->addRoute();

        // 7. 更新 Category 模型
        $this->updateCategoryModel();

        // 8. 自动执行 Seeders
        if (!$this->option('skip-seed')) {
            $this->runSeeders();
        }

        $this->info('🎉 RjYst Sentence 扩展包安装完成！');
        $this->showNextSteps();
    }

    /**
     * 自动执行 Seeders
     */
    protected function runSeeders()
    {
        $this->info('🌱 开始执行数据填充...');

        // 执行菜单 Seeder
        $this->runSeeder('SentenceMenuSeeder', '菜单数据');

        // 执行数据 Seeder
        $this->runSeeder('SentenceDataSeeder', '常用表达法数据');
    }

    /**
     * 执行单个 Seeder
     */
    protected function runSeeder($seederClass, $description)
    {
        try {
            $this->info("正在填充 {$description}...");

            $exitCode = Artisan::call('db:seed', [
                '--class' => $seederClass,
                '--force' => true
            ]);

            if ($exitCode === 0) {
                $this->info("✅ {$description}填充完成");

                // 显示 Artisan 命令的输出
                $output = Artisan::output();
                if ($output) {
                    $this->line($output);
                }
            } else {
                $this->warn("⚠️  {$description}填充可能有问题");
            }

        } catch (\Exception $e) {
            $this->error("❌ {$description}填充失败: " . $e->getMessage());

            // 如果是数据 Seeder 失败，提供手动执行的提示
            if ($seederClass === 'SentenceDataSeeder') {
                $this->warn('💡 可能是因为缺少源数据连接，你可以稍后手动执行：');
                $this->line("php artisan db:seed --class={$seederClass}");
            }
        }
    }

    protected function checkDependencies()
    {
        $this->info('检查依赖扩展包...');

        $dependencies = [
            'App\Models\Data\ClickLearn' => [
                'name' => '意识听资源内容管理扩展包',
                'install_command' => 'php artisan click-learn:install'
            ],
            'App\Models\Category\Category' => [
                'name' => '意识听年级管理扩展包',
                'install_command' => 'php artisan category:install'
            ]
        ];

        $missingDependencies = [];

        foreach ($dependencies as $class => $info) {
            if (!class_exists($class)) {
                $this->error("❌ 缺少依赖: {$info['name']}");
                $this->line("请先运行: {$info['install_command']}");
                $missingDependencies[] = $info['name'];
            } else {
                $this->info("✅ 依赖检查通过: {$info['name']}");
            }
        }

        if (!empty($missingDependencies)) {
            $this->error('请先安装依赖扩展包后再继续！');
            return false;
        }

        return true;
    }

    protected function publishMigrations()
    {
        $this->info('发布迁移文件...');

        $this->call('vendor:publish', ['--tag' => 'rj-sentence-migrations']);

        // 检查表是否存在，不存在则运行迁移
        if (!Schema::hasTable('often_expressions')) {
            $this->info('often_expressions 表不存在，正在创建...');
            $this->runSpecificMigration('2025_09_10_025209_create_often_expressions_table.php');
        } else {
            $this->info('✅ often_expressions 表已存在');
        }
    }

    protected function runSpecificMigration($filename)
    {
        try {
            Artisan::call('migrate', ['--path' => 'database/migrations/' . $filename]);
            $this->info("✅ {$filename} 迁移完成");
        } catch (\Exception $e) {
            $this->error("迁移失败: " . $e->getMessage());
        }
    }

    protected function publishModels()
    {
        $this->info('发布模型文件...');

        $this->call('vendor:publish', ['--tag' => 'rj-sentence-models']);

        // 检查模型是否存在
        $sentenceModel = app_path('Models/Sentence/Sentence.php');

        if (File::exists($sentenceModel)) {
            $this->info('✅ Sentence 模型已存在，跳过');
        } else {
            $this->info('✅ Sentence 模型创建完成');
        }
    }

    protected function publishAdminFiles()
    {
        $this->info('发布管理后台文件...');

        // 发布控制器
        $this->call('vendor:publish', ['--tag' => 'rj-sentence-controllers']);

        // 发布仓库
        $this->call('vendor:publish', ['--tag' => 'rj-sentence-repositories']);

        // 检查管理后台文件是否存在
        $files = [
            'OftenExpressionController' => app_path('Admin/Controllers/Sentence/OftenExpressionController.php'),
            'OftenExpression Repository' => app_path('Admin/Repositories/Sentence/OftenExpression.php'),
        ];

        foreach ($files as $name => $path) {
            if (File::exists($path)) {
                $this->info("✅ {$name} 已存在，跳过");
            } else {
                $this->info("✅ {$name} 创建完成");
            }
        }
    }

    protected function publishSeeders()
    {
        $this->info('发布 Seeder 文件...');

        $this->call('vendor:publish', ['--tag' => 'rj-sentence-seeders']);

        $seeders = [
            'SentenceDataSeeder.php' => database_path('seeders/SentenceDataSeeder.php'),
            'SentenceMenuSeeder.php' => database_path('seeders/SentenceMenuSeeder.php'),
        ];

        foreach ($seeders as $name => $path) {
            if (File::exists($path)) {
                $this->info("✅ {$name} 已存在，跳过");
            } else {
                $this->info("✅ {$name} 创建完成");
            }
        }
    }

    protected function addRoute()
    {
        $this->info('添加路由...');

        $routeFile = app_path('Admin/routes.php');
        $routeLine = "    \$router->resource('sentence', 'Sentence\\OftenExpressionController');";

        if (!File::exists($routeFile)) {
            $this->warn('⚠️  Admin routes.php 文件不存在，请手动添加路由');
            return;
        }

        $content = File::get($routeFile);

        // 检查路由是否已存在
        if (strpos($content, "sentence") !== false) {
            $this->info('✅ 路由已存在');
            return;
        }

        // 查找 }); 的位置，在其前面添加路由
        $closingPattern = '});';
        $position = strrpos($content, $closingPattern);

        if ($position !== false) {
            // 在 }); 前面添加新路由
            $beforeClosing = substr($content, 0, $position);
            $afterClosing = substr($content, $position);

            // 确保有适当的换行
            $newContent = rtrim($beforeClosing) . "\n" . $routeLine . "\n" . $afterClosing;

            File::put($routeFile, $newContent);
            $this->info('✅ 路由添加完成');
        } else {
            $this->warn('⚠️  无法找到路由文件结构，请手动添加路由：');
            $this->line($routeLine);
        }
    }

    protected function updateCategoryModel()
    {
        $this->info('更新 Category 模型...');

        $categoryModelPath = app_path('Models/Category/Category.php');

        if (!File::exists($categoryModelPath)) {
            $this->warn('⚠️  Category 模型不存在，请先安装年级管理扩展包');
            return;
        }

        $content = File::get($categoryModelPath);

        // 检查是否已经包含 Sentence 相关代码
        if (strpos($content, 'use App\Models\Sentence\Sentence;') !== false) {
            $this->info('✅ Category 模型已包含 Sentence 关联');
            return;
        }

        // 1. 添加 use 语句
        $useStatement = 'use App\Models\Sentence\Sentence;';
        $namespaceDeclaration = 'namespace App\Models\Category;';

        if (strpos($content, $namespaceDeclaration) !== false) {
            $content = str_replace(
                $namespaceDeclaration,
                $namespaceDeclaration . "\n\n" . $useStatement,
                $content
            );
        }

        // 2. 添加关联方法
        $relationshipMethod = "
    public function sentence(): Relations\HasMany
    {
        return \$this->hasMany(Sentence::class);
    }";

        // 在最后一个大括号前添加方法
        $lastBracePos = strrpos($content, '}');
        if ($lastBracePos !== false) {
            $content = substr_replace($content, $relationshipMethod . "\n}", $lastBracePos, 1);
        }

        File::put($categoryModelPath, $content);
        $this->info('✅ Category 模型更新完成');
    }

    protected function showNextSteps()
    {
        $this->line('');
        $this->line('<fg=green>🎉 安装完成！功能已就绪：</>');
        $this->line('✅ 数据表已创建');
        $this->line('✅ 模型文件已生成');
        $this->line('✅ 管理后台已配置');
        $this->line('✅ 路由已添加');
        $this->line('✅ 菜单已创建');
        $this->line('✅ 数据已导入');
        $this->line('');
        $this->line('<fg=yellow>📋 可用功能：</>');
        $this->line('• 访问管理后台: 模块管理 -> 常用表达法');
        $this->line('• 管理常用表达法内容');
        $this->line('• 按年级和单元筛选');
        $this->line('');

        if ($this->option('skip-seed')) {
            $this->line('<fg=blue>🔧 手动执行数据填充：</>');
            $this->line('• 导入菜单: <fg=green>php artisan db:seed --class=SentenceMenuSeeder</>');
            $this->line('• 导入数据: <fg=green>php artisan db:seed --class=SentenceDataSeeder</>');
            $this->line('');
        } else {
            $this->line('<fg=blue>🔧 重新执行数据填充（如果需要）：</>');
            $this->line('• 重新导入菜单: <fg=green>php artisan db:seed --class=SentenceMenuSeeder</>');
            $this->line('• 重新导入数据: <fg=green>php artisan db:seed --class=SentenceDataSeeder</>');
            $this->line('');
        }

        $this->line('<fg=red>卸载：</>');
        $this->line('如需卸载扩展包，请运行: <fg=red>php artisan rj-sentence:uninstall</>');
    }
}
